<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">化工厂分布图</text>
      <view class="controls">
        <button class="btn" @click="refreshData">刷新数据</button>
        <button class="btn" @click="toggleView">{{ isListView ? '地图视图' : '列表视图' }}</button>
      </view>
    </view>

    <!-- 地图视图 -->
    <view class="map-container" v-if="!isListView">
      <map 
        id="factoryMap"
        :longitude="mapCenter.longitude"
        :latitude="mapCenter.latitude"
        :markers="mapMarkers"
        :scale="16"
        :show-location="true"
        @markertap="onMarkerTap"
        @updated="onMapUpdated"
        @error="onMapError"
        class="map"
      ></map>
      
      <!-- 地图图例 -->
      <view class="legend">
        <view class="legend-item">
          <view class="legend-dot high-risk"></view>
          <text>高风险</text>
        </view>
        <view class="legend-item">
          <view class="legend-dot medium-risk"></view>
          <text>中风险</text>
        </view>
        <view class="legend-item">
          <view class="legend-dot low-risk"></view>
          <text>低风险</text>
        </view>
      </view>
    </view>

    <!-- 列表视图 -->
    <view class="list-container" v-if="isListView">
      <view class="factory-item" v-for="factory in factoryList" :key="factory.factoryId" @click="selectFactory(factory)">
        <view class="factory-info">
          <text class="factory-name">{{ factory.factoryName }}</text>
          <text class="factory-address">{{ factory.address }}</text>
          <text class="factory-type">{{ factory.factoryType }}</text>
        </view>
        <view class="factory-risk" :class="getRiskClass(factory.riskLevel)">
          <text>{{ getRiskText(factory.riskLevel) }}</text>
        </view>
      </view>
    </view>

    <!-- 工厂详情弹窗 -->
    <view class="popup" v-if="showDetailPopup" @click="closeDetailPopup">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">{{ selectedFactory?.factoryName }}</text>
          <text class="popup-close" @click="closeDetailPopup">×</text>
        </view>
        <view class="popup-body">
          <view class="info-row">
            <text class="label">工厂编码：</text>
            <text class="value">{{ selectedFactory?.factoryCode }}</text>
          </view>
          <view class="info-row">
            <text class="label">地址：</text>
            <text class="value">{{ selectedFactory?.address }}</text>
          </view>
          <view class="info-row">
            <text class="label">工厂类型：</text>
            <text class="value">{{ selectedFactory?.factoryType }}</text>
          </view>
          <view class="info-row">
            <text class="label">主要污染物：</text>
            <text class="value">{{ selectedFactory?.mainPollutants }}</text>
          </view>
          <view class="info-row">
            <text class="label">风险等级：</text>
            <text class="value" :class="getRiskClass(selectedFactory?.riskLevel)">{{ getRiskText(selectedFactory?.riskLevel) }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-primary" @click="startPrediction">开始预测</button>
          <button class="btn-warning" @click="showPredictionOptions">预测选项</button>
          <button class="btn-info" @click="viewAnalysisHistory">查看历史</button>
          <button class="btn-secondary" @click="closeDetailPopup">关闭</button>
        </view>
      </view>
    </view>

    <!-- 预测选项弹窗 -->
    <view class="popup" v-if="showPredictionPopup" @click="closePredictionPopup">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">污染预测选项</text>
          <text class="popup-close" @click="closePredictionPopup">×</text>
        </view>
        <view class="popup-body">
          <view class="prediction-options">
            <view class="option-item" @click="runFactoryAnalysis">
              <view class="option-icon">🏭</view>
              <view class="option-content">
                <text class="option-title">化工厂分析</text>
                <text class="option-desc">AI分析工厂风险等级</text>
              </view>
            </view>
            
            <view class="option-item" @click="showDiffusionPathParams">
              <view class="option-icon">🌪️</view>
              <view class="option-content">
                <text class="option-title">扩散路径定位</text>
                <text class="option-desc">预测污染物扩散路径</text>
              </view>
            </view>
            
            <view class="option-item" @click="showPollutionPredictionParams">
              <view class="option-icon">📊</view>
              <view class="option-content">
                <text class="option-title">污染预测模型</text>
                <text class="option-desc">预测污染趋势变化</text>
              </view>
            </view>
            
            <view class="option-item" @click="showRiskAssessmentParams">
              <view class="option-icon">📋</view>
              <view class="option-content">
                <text class="option-title">风险评估报告</text>
                <text class="option-desc">生成详细风险评估</text>
              </view>
            </view>
            
            <view class="option-item" @click="showEarlyWarningParams">
              <view class="option-icon">⚠️</view>
              <view class="option-content">
                <text class="option-title">预警机制</text>
                <text class="option-desc">智能预警分析</text>
              </view>
            </view>
            
            <view class="option-item" @click="showImpactAssessmentParams">
              <view class="option-icon">🎯</view>
              <view class="option-content">
                <text class="option-title">影响评估</text>
                <text class="option-desc">评估污染影响范围</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 扩散路径参数设置弹窗 -->
    <view class="popup" v-if="showDiffusionParams" @click="closeDiffusionParams">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">扩散路径参数设置</text>
          <text class="popup-close" @click="closeDiffusionParams">×</text>
        </view>
        <view class="popup-body">
          <!-- 自动获取天气数据按钮 -->
          <view class="weather-section">
            <button class="btn-weather" @click="loadWeatherData" :disabled="weatherLoading">
              {{ weatherLoading ? '获取中...' : '🌤️ 自动获取实时天气' }}
            </button>
            <text class="weather-info" v-if="weatherData.city">
              当前城市：{{ weatherData.city }} | 更新时间：{{ weatherData.reportTime }}
            </text>
            <text class="weather-info" v-if="selectedFactory">
              工厂地址：{{ selectedFactory.address }}
            </text>
          </view>
          
          <view class="param-form">
            <view class="form-item">
              <text class="form-label">风向：</text>
              <picker @change="onWindDirectionChange" :value="windDirectionIndex" :range="windDirections">
                <view class="picker">
                  {{ windDirections[windDirectionIndex] }}
                </view>
              </picker>
            </view>
            
            <view class="form-item">
              <text class="form-label">风速：</text>
              <input class="input" type="number" v-model="windSpeed" placeholder="请输入风速(m/s)" />
            </view>
            
            <view class="form-item">
              <text class="form-label">温度：</text>
              <input class="input" type="number" v-model="temperature" placeholder="请输入温度(℃)" />
            </view>
            
            <view class="form-item">
              <text class="form-label">湿度：</text>
              <input class="input" type="number" v-model="humidity" placeholder="请输入湿度(%)" />
            </view>
            
            <view class="form-item">
              <text class="form-label">气压：</text>
              <input class="input" type="number" v-model="pressure" placeholder="请输入气压(hPa)" />
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-primary" @click="runDiffusionPath">开始分析</button>
          <button class="btn-secondary" @click="closeDiffusionParams">取消</button>
        </view>
      </view>
    </view>

    <!-- 污染预测参数设置弹窗 -->
    <view class="popup" v-if="showPollutionParams" @click="closePollutionParams">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">污染预测参数设置</text>
          <text class="popup-close" @click="closePollutionParams">×</text>
        </view>
        <view class="popup-body">
          <view class="param-form">
            <view class="form-item">
              <text class="form-label">预测时长：</text>
              <picker @change="onHoursChange" :value="hoursIndex" :range="predictionHours">
                <view class="picker">
                  {{ predictionHours[hoursIndex] }}
                </view>
              </picker>
            </view>
            
            <view class="form-item">
              <text class="form-label">当前浓度：</text>
              <input class="input" type="number" v-model="currentConcentration" placeholder="请输入当前浓度" />
            </view>
            
            <view class="form-item">
              <text class="form-label">环境条件：</text>
              <picker @change="onConditionChange" :value="conditionIndex" :range="environmentalConditions">
                <view class="picker">
                  {{ environmentalConditions[conditionIndex] }}
                </view>
              </picker>
            </view>
            
            <view class="form-item">
              <text class="form-label">污染物类型：</text>
              <picker @change="onPollutantChange" :value="pollutantIndex" :range="pollutantTypes">
                <view class="picker">
                  {{ pollutantTypes[pollutantIndex] }}
                </view>
              </picker>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-primary" @click="runPollutionPrediction">开始预测</button>
          <button class="btn-secondary" @click="closePollutionParams">取消</button>
        </view>
      </view>
    </view>

    <!-- 预警参数设置弹窗 -->
    <view class="popup" v-if="showWarningParams" @click="closeWarningParams">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">预警参数设置</text>
          <text class="popup-close" @click="closeWarningParams">×</text>
        </view>
        <view class="popup-body">
          <view class="param-form">
            <view class="form-item">
              <text class="form-label">当前浓度：</text>
              <input class="input" type="number" v-model="currentLevel" placeholder="请输入当前污染物浓度" />
            </view>
            
            <view class="form-item">
              <text class="form-label">预警阈值：</text>
              <input class="input" type="number" v-model="threshold" placeholder="请输入预警阈值" />
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-primary" @click="runEarlyWarning">开始预警分析</button>
          <button class="btn-secondary" @click="closeWarningParams">取消</button>
        </view>
      </view>
    </view>

    <!-- 预测结果弹窗 -->
    <view class="popup" v-if="showResultPopup" @click="closeResultPopup">
      <view class="popup-content result-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">{{ resultTitle }}</text>
          <text class="popup-close" @click="closeResultPopup">×</text>
        </view>
        <view class="popup-body">
          <view class="result-content">
            <text class="result-text">{{ predictionResult }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-secondary" @click="closeResultPopup">关闭</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { pollutionApi } from '@/api/pollution.js'
import { getRealtimeWeather, getNearbySchools, getNearbyHospitals, getNearbyResidential } from '@/api/weather.js'

export default {
  data() {
    return {
      factoryList: [], // 化工厂列表
      mapCenter: {
        longitude: 114.305392, // 默认中心点（武汉）
        latitude: 30.592849
      },
      mapMarkers: [], // 地图标记点
      isListView: false, // 是否列表视图
      showDetailPopup: false, // 是否显示详情弹窗
      showPredictionPopup: false, // 是否显示预测选项弹窗
      showResultPopup: false, // 是否显示结果弹窗
      selectedFactory: null, // 选中的工厂
      mapLoaded: false, // 地图是否加载完成
      predictionResult: '', // 预测结果
      resultTitle: '', // 结果标题
      
      // 参数设置弹窗控制
      showDiffusionParams: false,
      showPollutionParams: false,
      showWarningParams: false,
      
      // 扩散路径参数
      windDirectionIndex: 0,
      windDirections: ['东北风', '东风', '东南风', '南风', '西南风', '西风', '西北风', '北风'],
      windSpeed: 3.5,
      temperature: 25.0,
      humidity: 65.0,
      pressure: 1013.25,
      
      // 污染预测参数
      hoursIndex: 0,
      predictionHours: ['6小时', '12小时', '24小时', '48小时', '72小时'],
      currentConcentration: 150.5,
      conditionIndex: 0,
      environmentalConditions: ['晴天，微风', '阴天，小风', '雨天，大风', '雾天，无风', '晴天，强风'],
      pollutantIndex: 0,
      pollutantTypes: ['PM2.5', 'PM10', 'SO2', 'NO2', 'CO', 'O3'],
      
      // 预警参数
      currentLevel: 180.5,
      threshold: 150.0,
      
      // 天气数据
      weatherLoading: false,
      weatherData: {
        city: '',
        reportTime: '',
        temperature: '25',
        humidity: '65',
        windDirection: '东北风',
        windSpeed: 3.5,
        weather: '晴',
        pressure: '1013.25'
      }
    }
  },
  
  onLoad() {
    this.loadFactoryData()
  },
  
  methods: {
    // 加载化工厂数据
    async loadFactoryData() {
      try {
        uni.showLoading({ title: '加载中...' })
        console.log('开始调用API...')
        
        const res = await pollutionApi.getFactoryAnalysis()
        console.log('API返回数据:', res)
        
        if (res.code === 200) {
          this.factoryList = res.obj || []
          console.log('工厂列表数据:', this.factoryList)
          this.createMapMarkers()
        } else {
          console.log('API返回错误:', res.msg)
          uni.showToast({
            title: res.msg || '加载失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        console.log('使用备用数据')
        this.createMapMarkers()
        
        uni.showToast({
          title: '使用备用数据',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 创建地图标记点
    createMapMarkers() {
      console.log('开始创建地图标记点，工厂数量:', this.factoryList.length)
      
      this.mapMarkers = this.factoryList.map(factory => {
        const marker = {
          id: factory.factoryId,
          latitude: factory.latitude,
          longitude: factory.longitude,
          title: factory.factoryName,
          iconPath: this.getMarkerIcon(factory.riskLevel),
          width: 30,
          height: 30,
          callout: {
            content: factory.factoryName,
            color: '#333',
            fontSize: 12,
            borderRadius: 5,
            bgColor: '#fff',
            padding: 5,
            display: 'ALWAYS'
          }
        }
        console.log('创建标记点:', marker)
        return marker
      })
      
      console.log('地图标记点创建完成:', this.mapMarkers)
    },
    
    // 获取标记点图标
    getMarkerIcon(riskLevel) {
      // 根据风险等级返回不同颜色的图标
      const icons = {
        1: '/static/icons/low-risk.svg',    // 低风险 - 绿色
        2: '/static/icons/medium-risk.svg', // 中风险 - 橙色  
        3: '/static/icons/high-risk.svg'    // 高风险 - 红色
      }
      return icons[riskLevel] || icons[2]
    },
    
    // 获取风险等级样式类
    getRiskClass(riskLevel) {
      const classes = {
        1: 'low-risk',
        2: 'medium-risk', 
        3: 'high-risk'
      }
      return classes[riskLevel] || 'medium-risk'
    },
    
    // 获取风险等级文本
    getRiskText(riskLevel) {
      const texts = {
        1: '低风险',
        2: '中风险',
        3: '高风险'
      }
      return texts[riskLevel] || '未知'
    },
    
    // 地图标记点击事件
    onMarkerTap(e) {
      const markerId = e.detail.markerId
      const factory = this.factoryList.find(f => f.factoryId === markerId)
      if (factory) {
        this.selectFactory(factory)
      }
    },
    
    // 选择工厂
    selectFactory(factory) {
      this.selectedFactory = factory
      this.showDetailPopup = true
    },
    
    // 关闭详情弹窗
    closeDetailPopup() {
      this.showDetailPopup = false
      this.selectedFactory = null
    },
    
    // 显示预测选项
    showPredictionOptions() {
      this.showPredictionPopup = true
    },
    
    // 关闭预测选项弹窗
    closePredictionPopup() {
      this.showPredictionPopup = false
    },
    
    // 关闭结果弹窗
    closeResultPopup() {
      this.showResultPopup = false
      this.predictionResult = ''
      this.resultTitle = ''
    },
    
    // 开始预测（原有功能）
    async startPrediction() {
      if (!this.selectedFactory) return
      
      try {
        uni.showLoading({ title: '预测中...' })
        const res = await pollutionApi.predictPollution(this.selectedFactory.factoryId, 24, {
          currentConcentration: 150.5,
          environmentalConditions: '晴天，微风',
          pollutantType: 'PM2.5'
        })
        
        if (res.code === 200) {
          this.predictionResult = res.obj.predictionResult || res.obj.analysisResult || '预测完成'
          this.resultTitle = '污染预测结果'
          this.showResultPopup = true
          
          uni.showToast({
            title: '预测完成',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '预测失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('预测失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 1. 化工厂分析
    async runFactoryAnalysis() {
      if (!this.selectedFactory) return
      
      try {
        uni.showLoading({ title: 'AI分析中...' })
        const res = await pollutionApi.analyzeFactory(this.selectedFactory.factoryId)
        
        if (res.code === 200) {
          this.predictionResult = res.obj.analysisResult || '分析完成'
          this.resultTitle = '化工厂分析结果'
          this.showResultPopup = true
          this.showPredictionPopup = false
          
          // 自动保存分析结果
          this.saveAnalysisResult('化工厂分析', res.obj.analysisResult)
          
          uni.showToast({
            title: '分析完成',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '分析失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('分析失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 显示扩散路径参数设置
    showDiffusionPathParams() {
      this.showDiffusionParams = true
      this.showPredictionPopup = false
    },
    
    // 关闭扩散路径参数设置
    closeDiffusionParams() {
      this.showDiffusionParams = false
    },
    
    // 风向变化
    onWindDirectionChange(e) {
      this.windDirectionIndex = e.detail.value
    },
    
    // 加载天气数据
    async loadWeatherData() {
      try {
        this.weatherLoading = true
        uni.showLoading({ title: '获取天气数据...' })
        
        // 根据选中的工厂确定城市
        let city = '武汉市' // 默认武汉
        if (this.selectedFactory && this.selectedFactory.address) {
          // 从工厂地址中提取城市
          const address = this.selectedFactory.address
          if (address.includes('郑州')) {
            city = '郑州市'
          } else if (address.includes('武汉')) {
            city = '武汉市'
          } else if (address.includes('北京')) {
            city = '北京市'
          } else if (address.includes('上海')) {
            city = '上海市'
          } else if (address.includes('广州')) {
            city = '广州市'
          } else if (address.includes('深圳')) {
            city = '深圳市'
          }
        }
        
        console.log('获取城市天气:', city)
        const result = await getRealtimeWeather(city)
        
        if (result.success) {
          this.weatherData = result.data
          console.log('天气数据:', result.data)
          
          // 自动填充参数
          this.temperature = result.data.temperature
          this.humidity = result.data.humidity
          this.pressure = result.data.pressure
          this.windSpeed = result.data.windSpeed
          
          // 设置风向 - 处理高德API的风向格式
          const apiWindDirection = result.data.windDirection
          console.log('API风向:', apiWindDirection)
          
          // 风向映射表
          const windMapping = {
            '北风': '北风',
            '东北风': '东北风', 
            '东风': '东风',
            '东南风': '东南风',
            '南风': '南风',
            '西南风': '西南风',
            '西风': '西风',
            '西北风': '西北风',
            '无风': '北风', // 无风时默认北风
            '微风': '北风'  // 微风时默认北风
          }
          
          const mappedWind = windMapping[apiWindDirection] || '北风'
          const windIndex = this.windDirections.findIndex(wind => wind === mappedWind)
          
          if (windIndex !== -1) {
            this.windDirectionIndex = windIndex
            console.log('设置风向索引:', windIndex, '风向:', mappedWind)
          } else {
            console.log('风向未找到匹配项:', apiWindDirection)
          }
          
          uni.showToast({
            title: `${city}天气数据获取成功`,
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '天气数据获取失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('获取天气数据失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
        this.weatherLoading = false
        uni.hideLoading()
      }
    },
    
    // 2. 扩散路径定位
    async runDiffusionPath() {
      if (!this.selectedFactory) return
      
      try {
        uni.showLoading({ title: '计算扩散路径...' })
        const weatherData = {
          windDirection: this.windDirections[this.windDirectionIndex],
          windSpeed: parseFloat(this.windSpeed),
          temperature: parseFloat(this.temperature),
          humidity: parseFloat(this.humidity),
          pressure: parseFloat(this.pressure)
        }
        
        const res = await pollutionApi.predictDiffusionPath(this.selectedFactory.factoryId, weatherData)
        
        if (res.code === 200) {
          this.predictionResult = res.obj.diffusionPath || '路径计算完成'
          this.resultTitle = '扩散路径分析'
          this.showResultPopup = true
          this.showDiffusionParams = false
          
          uni.showToast({
            title: '计算完成',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '计算失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('计算失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 显示污染预测参数设置
    showPollutionPredictionParams() {
      this.showPollutionParams = true
      this.showPredictionPopup = false
    },
    
    // 关闭污染预测参数设置
    closePollutionParams() {
      this.showPollutionParams = false
    },
    
    // 预测时长变化
    onHoursChange(e) {
      this.hoursIndex = e.detail.value
    },
    
    // 环境条件变化
    onConditionChange(e) {
      this.conditionIndex = e.detail.value
    },
    
    // 污染物类型变化
    onPollutantChange(e) {
      this.pollutantIndex = e.detail.value
    },
    
    // 3. 污染预测模型
    async runPollutionPrediction() {
      if (!this.selectedFactory) return
      
      try {
        uni.showLoading({ title: '预测污染趋势...' })
        const hours = parseInt(this.predictionHours[this.hoursIndex])
        const currentData = {
          currentConcentration: parseFloat(this.currentConcentration),
          environmentalConditions: this.environmentalConditions[this.conditionIndex],
          pollutantType: this.pollutantTypes[this.pollutantIndex]
        }
        
        const res = await pollutionApi.predictPollution(this.selectedFactory.factoryId, hours, currentData)
        
        if (res.code === 200) {
          this.predictionResult = res.obj.predictionResult || '预测完成'
          this.resultTitle = '污染预测结果'
          this.showResultPopup = true
          this.showPollutionParams = false
          
          uni.showToast({
            title: '预测完成',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '预测失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('预测失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 4. 风险评估报告
    async runRiskAssessment() {
      if (!this.selectedFactory) return
      
      try {
        uni.showLoading({ title: '生成风险评估报告...' })
        
        // 使用动态参数，基于工厂实际信息
        const riskFactors = {
          riskFactors: this.generateRiskFactors(),
          surroundingEnvironment: this.generateSurroundingEnvironment(),
          historicalAccidents: this.generateHistoricalAccidents(),
          safetyMeasures: this.generateSafetyMeasures()
        }
        
        console.log('风险评估参数:', riskFactors)
        
        const res = await pollutionApi.generateRiskAssessment(this.selectedFactory.factoryId, riskFactors)
        
        if (res.code === 200) {
          this.predictionResult = res.obj.assessmentReport || '报告生成完成'
          this.resultTitle = '风险评估报告'
          this.showResultPopup = true
          this.showPredictionPopup = false
          
          uni.showToast({
            title: '报告生成完成',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '报告生成失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('报告生成失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 根据工厂信息生成风险因素
    generateRiskFactors() {
      const factory = this.selectedFactory
      let riskFactors = []
      
      // 基于工厂类型判断风险
      if (factory.factoryType && factory.factoryType.includes('化工')) {
        riskFactors.push('化工生产高风险')
      }
      if (factory.factoryType && factory.factoryType.includes('制造')) {
        riskFactors.push('工业制造污染')
      }
      
      // 基于污染物判断风险
      if (factory.mainPollutants) {
        if (factory.mainPollutants.includes('重金属')) {
          riskFactors.push('重金属污染风险')
        }
        if (factory.mainPollutants.includes('COD') || factory.mainPollutants.includes('氨氮')) {
          riskFactors.push('水体污染风险')
        }
      }
      
      // 基于地址判断风险
      if (factory.address) {
        if (factory.address.includes('居民') || factory.address.includes('住宅')) {
          riskFactors.push('靠近居民区')
        }
        if (factory.address.includes('学校') || factory.address.includes('医院')) {
          riskFactors.push('靠近敏感区域')
        }
      }
      
      return riskFactors.length > 0 ? riskFactors.join('，') : '需要进一步评估'
    },
    
    // 根据工厂地址生成周边环境描述
    generateSurroundingEnvironment() {
      const factory = this.selectedFactory
      if (!factory.address) return '需要实地调研确定'
      
      const address = factory.address
      let environment = []
      
      // 基于地址关键词判断周边环境
      if (address.includes('工业') || address.includes('园区')) {
        environment.push('工业区')
      }
      if (address.includes('居民') || address.includes('住宅')) {
        environment.push('居民区')
      }
      if (address.includes('学校') || address.includes('教育')) {
        environment.push('教育区域')
      }
      if (address.includes('医院') || address.includes('医疗')) {
        environment.push('医疗区域')
      }
      if (address.includes('商业') || address.includes('市场')) {
        environment.push('商业区域')
      }
      
      return environment.length > 0 ? environment.join('、') + '周边' : '需要实地调研确定'
    },
    
    // 生成历史事故信息（模拟）
    generateHistoricalAccidents() {
      const factory = this.selectedFactory
      if (!factory.factoryName) return '暂无历史事故记录'
      
      // 基于工厂名称生成模拟的历史信息
      const factoryName = factory.factoryName
      if (factoryName.includes('A') || factoryName.includes('1')) {
        return '2021年发生轻微设备故障，已及时处理'
      } else if (factoryName.includes('B') || factoryName.includes('2')) {
        return '2022年发生轻微泄漏事件，已整改完成'
      } else if (factoryName.includes('C') || factoryName.includes('3')) {
        return '2023年发生环保超标，已升级处理设施'
      } else {
        return '暂无重大历史事故记录，运行状况良好'
      }
    },
    
    // 生成安全措施信息
    generateSafetyMeasures() {
      const factory = this.selectedFactory
      let measures = []
      
      // 基于工厂类型生成相应的安全措施
      if (factory.factoryType && factory.factoryType.includes('化工')) {
        measures.push('化工安全防护设施')
        measures.push('应急处理设备')
      }
      
      measures.push('环境监测设备')
      measures.push('安全管理制度')
      measures.push('员工安全培训')
      
      return measures.join('、')
    },
    
    // 显示预警参数设置
    showEarlyWarningParams() {
      this.showWarningParams = true
      this.showPredictionPopup = false
    },
    
    // 关闭预警参数设置
    closeWarningParams() {
      this.showWarningParams = false
    },
    
    // 5. 预警机制
    async runEarlyWarning() {
      if (!this.selectedFactory) return
      
      try {
        uni.showLoading({ title: '分析预警等级...' })
        const res = await pollutionApi.generateEarlyWarning(
          this.selectedFactory.factoryId, 
          parseFloat(this.currentLevel), 
          parseFloat(this.threshold)
        )
        
        if (res.code === 200) {
          this.predictionResult = res.obj.warningResult || '预警分析完成'
          this.resultTitle = '预警分析结果'
          this.showResultPopup = true
          this.showWarningParams = false
          
          uni.showToast({
            title: '预警分析完成',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '预警分析失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('预警分析失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 显示风险评估参数设置
    showRiskAssessmentParams() {
      // 暂时直接运行，后续可以添加参数设置
      this.runRiskAssessment()
    },
    
    // 显示影响评估参数设置
    showImpactAssessmentParams() {
      // 暂时直接运行，后续可以添加参数设置
      this.runImpactAssessment()
    },
    
    // 6. 影响评估
    async runImpactAssessment() {
      if (!this.selectedFactory) return
      
      try {
        uni.showLoading({ title: '评估影响范围...' })
        
        // 基于工厂信息生成动态影响评估参数
        const sensitiveTargets = {
          sensitiveTargets: await this.generateSensitiveTargets(),
          populationDensity: this.generatePopulationDensity(),
          vulnerableGroups: this.generateVulnerableGroups(),
          distance: this.generateDistanceInfo()
        }
        
        const impactArea = this.generateImpactArea()
        
        console.log('影响评估参数:', { impactArea, sensitiveTargets })
        
        const res = await pollutionApi.assessImpact(this.selectedFactory.factoryId, impactArea, sensitiveTargets)
        
        if (res.code === 200) {
          this.predictionResult = res.obj.impactAssessment || '影响评估完成'
          this.resultTitle = '影响评估结果'
          this.showResultPopup = true
          this.showPredictionPopup = false
          
          uni.showToast({
            title: '影响评估完成',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '影响评估失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('影响评估失败:', error)
        uni.showToast({
          title: '网络错误',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 生成敏感目标信息 - 使用高德API获取真实数据
    async generateSensitiveTargets() {
      const factory = this.selectedFactory
      if (!factory.longitude || !factory.latitude) {
        return '需要工厂经纬度信息'
      }
      
      try {
        console.log('获取工厂周边敏感目标:', factory.longitude, factory.latitude)
        
        // 并行获取周边POI信息
        const [schoolsResult, hospitalsResult, residentialResult] = await Promise.all([
          getNearbySchools(factory.longitude, factory.latitude, 3000),
          getNearbyHospitals(factory.longitude, factory.latitude, 3000),
          getNearbyResidential(factory.longitude, factory.latitude, 3000)
        ])
        
        let targets = []
        
        // 处理学校信息
        if (schoolsResult.success && schoolsResult.data.length > 0) {
          const schoolCount = schoolsResult.data.length
          const nearestSchool = schoolsResult.data[0]
          targets.push(`${schoolCount}所学校（最近：${nearestSchool.name}，距离${nearestSchool.distance}米）`)
        }
        
        // 处理医院信息
        if (hospitalsResult.success && hospitalsResult.data.length > 0) {
          const hospitalCount = hospitalsResult.data.length
          const nearestHospital = hospitalsResult.data[0]
          targets.push(`${hospitalCount}所医院（最近：${nearestHospital.name}，距离${nearestHospital.distance}米）`)
        }
        
        // 处理居民区信息
        if (residentialResult.success && residentialResult.data.length > 0) {
          const residentialCount = residentialResult.data.length
          const nearestResidential = residentialResult.data[0]
          targets.push(`${residentialCount}个居民区（最近：${nearestResidential.name}，距离${nearestResidential.distance}米）`)
        }
        
        console.log('敏感目标分析结果:', targets)
        return targets.length > 0 ? targets.join('；') : '周边3公里内无敏感目标'
        
      } catch (error) {
        console.error('获取敏感目标失败:', error)
        return '获取周边信息失败，请检查网络连接'
      }
    },
    
    // 生成人口密度信息
    generatePopulationDensity() {
      const factory = this.selectedFactory
      if (!factory.address) return '需要实地调研确定'
      
      const address = factory.address
      
      // 基于地址关键词判断人口密度
      if (address.includes('市中心') || address.includes('商业')) {
        return '高密度'
      } else if (address.includes('居民') || address.includes('住宅')) {
        return '中高密度'
      } else if (address.includes('工业') || address.includes('园区')) {
        return '中密度'
      } else {
        return '需要实地调研确定'
      }
    },
    
    // 生成易感人群信息
    generateVulnerableGroups() {
      const factory = this.selectedFactory
      let groups = ['老人', '儿童']
      
      // 基于污染物类型判断易感人群
      if (factory.mainPollutants) {
        if (factory.mainPollutants.includes('重金属')) {
          groups.push('孕妇')
        }
        if (factory.mainPollutants.includes('PM2.5') || factory.mainPollutants.includes('PM10')) {
          groups.push('呼吸系统疾病患者')
        }
      }
      
      return groups.join('、')
    },
    
    // 生成距离信息
    generateDistanceInfo() {
      const factory = this.selectedFactory
      if (!factory.address) {
        return {
          nearestSchool: '需要实地测量',
          nearestHospital: '需要实地测量',
          nearestResidential: '需要实地测量'
        }
      }
      
      // 基于地址关键词模拟距离
      const address = factory.address
      let distances = {
        nearestSchool: 1000,
        nearestHospital: 1500,
        nearestResidential: 800
      }
      
      if (address.includes('学校')) {
        distances.nearestSchool = 500
      }
      if (address.includes('医院')) {
        distances.nearestHospital = 800
      }
      if (address.includes('居民')) {
        distances.nearestResidential = 300
      }
      
      return distances
    },
    
    // 生成影响区域
    generateImpactArea() {
      const factory = this.selectedFactory
      if (!factory.factoryType) return '周边3公里'
      
      // 基于工厂类型判断影响范围
      if (factory.factoryType.includes('化工')) {
        return '周边5公里'
      } else if (factory.factoryType.includes('制造')) {
        return '周边3公里'
      } else {
        return '周边2公里'
      }
    },
    
    // 刷新数据
    refreshData() {
      this.loadFactoryData()
    },
    
    // 切换视图
    toggleView() {
      this.isListView = !this.isListView
    },
    
    // 地图更新完成事件
    onMapUpdated(e) {
      console.log('地图更新完成:', e)
      this.mapLoaded = true
    },
    
    // 地图加载失败事件
    onMapError(e) {
      console.error('地图加载失败:', e)
      uni.showToast({
        title: '地图加载失败',
        icon: 'error'
      })
    },
    
    // 保存分析结果到数据库
    async saveAnalysisResult(analysisType, analysisResult) {
      try {
        console.log('保存分析结果:', analysisType, analysisResult)
        
        const analysisData = {
          analysisType: analysisType,
          analysisResult: analysisResult,
          factoryInfo: {
            factoryId: this.selectedFactory.factoryId,
            factoryName: this.selectedFactory.factoryName,
            factoryType: this.selectedFactory.factoryType,
            address: this.selectedFactory.address
          },
          timestamp: new Date().toISOString()
        }
        
        const saveRes = await pollutionApi.saveFactoryAnalysis(this.selectedFactory.factoryId, analysisData)
        
        if (saveRes.code === 200) {
          console.log('分析结果保存成功:', saveRes.obj)
        } else {
          console.log('分析结果保存失败:', saveRes.msg)
        }
      } catch (error) {
        console.error('保存分析结果失败:', error)
      }
    },
    
    // 查看分析历史
    async viewAnalysisHistory() {
      if (!this.selectedFactory) return
      
      try {
        uni.showLoading({ title: '加载历史记录...' })
        const res = await pollutionApi.getAnalysisHistory(this.selectedFactory.factoryId)
        
        if (res.code === 200) {
          console.log('分析历史:', res.obj)
          uni.showToast({
            title: '历史记录加载完成',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '暂无历史记录',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载历史记录失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.header {
  background: #fff;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.controls {
  display: flex;
  gap: 20rpx;
}

.btn {
  padding: 10rpx 20rpx;
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.map-container {
  flex: 1;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.legend {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background: rgba(255, 255, 255, 0.9);
  padding: 20rpx;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 24rpx;
}

.legend-dot {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
}

.high-risk {
  background: #ff4757;
}

.medium-risk {
  background: #ffa502;
}

.low-risk {
  background: #2ed573;
}

.list-container {
  flex: 1;
  padding: 20rpx;
}

.factory-item {
  background: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
  border-radius: 10rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.factory-info {
  flex: 1;
}

.factory-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.factory-address {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 5rpx;
}

.factory-type {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.factory-risk {
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #fff;
}

.popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.popup-content {
  background: #fff;
  width: 80%;
  max-width: 600rpx;
  border-radius: 20rpx;
  overflow: hidden;
}

.result-popup {
  max-width: 800rpx;
  max-height: 80vh;
}

.popup-header {
  background: #007aff;
  color: #fff;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
}

.popup-close {
  font-size: 40rpx;
  cursor: pointer;
}

.popup-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.info-row {
  display: flex;
  margin-bottom: 20rpx;
}

.label {
  width: 160rpx;
  font-size: 28rpx;
  color: #666;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.popup-footer {
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
}

.btn-primary {
  flex: 1;
  padding: 20rpx;
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.btn-warning {
  flex: 1;
  padding: 20rpx;
  background: #ff9500;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.btn-secondary {
  flex: 1;
  padding: 20rpx;
  background: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.btn-info {
  flex: 1;
  padding: 20rpx;
  background: #17a2b8;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  margin-left: 10rpx;
}

.prediction-options {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 10rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s;
}

.option-item:active {
  background: #e9ecef;
  border-color: #007aff;
}

.option-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.option-content {
  flex: 1;
}

.option-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}

.option-desc {
  font-size: 24rpx;
  color: #666;
  display: block;
}

.result-content {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 10rpx;
  border: 1rpx solid #e9ecef;
}

.result-text {
  font-size: 26rpx;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  word-break: break-word;
}

.param-form {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  width: 160rpx;
}

.picker {
  flex: 1;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 10rpx;
  border: 2rpx solid #e9ecef;
  font-size: 28rpx;
  color: #333;
}

.input {
  flex: 1;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 10rpx;
  border: 2rpx solid #e9ecef;
  font-size: 28rpx;
  color: #333;
}

.weather-section {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f0f8ff;
  border-radius: 10rpx;
  border: 1rpx solid #e6f3ff;
}

.btn-weather {
  width: 100%;
  padding: 20rpx;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 15rpx;
}

.btn-weather:disabled {
  background: #ccc;
  color: #999;
}

.weather-info {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  display: block;
}
</style>